//
//  WebService.m
//  OASystemManage
//
//  Created by joker on 15/7/21.
//  Copyright (c) 2015年 刘宣佚. All rights reserved.
//

#import "WebService.h"
#import  "ServerRequestUtility.h"
#import  <UIKit/UIKit.h>

@implementation WebService

- (id)initWithURL:(NSURL *)url AndRequestParam:(NSDictionary *)params Delegate:(id<WebServiceDelegate>)delegate
{
    if (self = [super init])
    {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
       
        NSError * error;
        NSData *paramsData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&error];
        if(!error){
            NSString *paramsString =[NSString stringWithFormat:@"content=%@", [[NSString alloc] initWithData:paramsData encoding:NSUTF8StringEncoding]];
            
            [request setHTTPBody:[paramsString dataUsingEncoding:NSUTF8StringEncoding]];
            
            connection = [NSURLConnection connectionWithRequest:request delegate:self];
            
            [connection start];
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
        }
        self.delegate = delegate;
    }
    return self;
}
- (NSString *)getReturnValue
{
    return returnValue;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (!receivedData)
    {
            // no store yet, make one
        receivedData = [[NSMutableData alloc] initWithData:data];
    }
    else
    {
            // append to previous chunks
        [receivedData appendData:data];
    }
}

    // all worked
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if(receivedData){
        NSDictionary * returnDict = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:nil];
        
        long int resultCode = [returnDict[@"Result"] integerValue];
        NSString *result = [NSString stringWithFormat:@"%ld",resultCode];
        NSString *resultMessage = [NSString stringWithFormat:@"%@", returnDict[@"ResultMessage"]];

        if([result isEqualToString:@"1"]) {
            if([resultMessage isEqualToString:@"100"])
            {
                returnValue = returnDict[@"ReturnValue"];
                [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                [self.delegate processReturnValue:self ReturnValue:returnValue];
            }
        }
        else
        {
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            NSString *title = [ServerRequestUtility showResult:result];
            NSString *body = [ServerRequestUtility showResultMessage:resultMessage];
            [ServerRequestUtility showAlertWithTitle:title MessageBody:body];
        }
    }
 }

    // and error occured
    -(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
        [ServerRequestUtility showAlertWithTitle:@"Request Error" MessageBody:error.userInfo[@"NSLocalizedDescription"]];
}


#pragma mark - NSURLConnectionDelegate
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
            //if ([trustedHosts containsObject:challenge.protectionSpace.host])
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
             forAuthenticationChallenge:challenge];
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
@end
